package com.appclub.kitsilano.bulletin;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import uk.co.senab.actionbarpulltorefresh.extras.PullToRefreshAttacher;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuItem;
import com.appclub.kitsilano.MainActivity;
import com.appclub.kitsilano.R;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Bulletin extends SherlockActivity implements
		PullToRefreshAttacher.OnRefreshListener {
	String[] list;
	int n = 0;
	int month;
	File file;
	File[] filelist;
	File[] filelist1;
	String[] ITEMS = { "PULL TO REFRESH" };
	PullToRefreshAttacher mPullToRefreshAttacher;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bulletin);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		Calendar c = Calendar.getInstance();
		month = c.get(Calendar.MONTH);

		try {
			String extStorageDirectory = Environment
					.getExternalStorageDirectory().toString();
			file = new File(extStorageDirectory + "/Kitsilano/");
			if (file.exists()) {
				filelist1 = file.listFiles();
				filelist = new File[filelist1.length];
				for (int i = 0; i < filelist1.length; i++) {
					filelist[i] = filelist1[filelist1.length - i - 1];
				}
			}
		} catch (Exception e) {
		}

		if (file != null && file.exists()) {
			ITEMS = new String[filelist.length];
			ITEMS = getFileName(filelist, ITEMS);
		}
		if (ITEMS.length <= 0) {
			ITEMS = new String[1];
			ITEMS[0] = "PULL TO REFRESH";
		}

		ListView lv = (ListView) findViewById(R.id.listView1);
		ListAdapter adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, ITEMS);
		lv.setAdapter(adapter);

		mPullToRefreshAttacher = new PullToRefreshAttacher(this);
		mPullToRefreshAttacher.setRefreshableView(lv, this);
		if (!ITEMS[0].equals("PULL TO REFRESH")) {
			lv.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					Intent intent = new Intent(Bulletin.this, PDFViewer.class);
					intent.putExtra("file", filelist[arg2].getName().toString());
					intent.putExtra("f", filelist[arg2].toString());
					startActivity(intent);
					overridePendingTransition(R.anim.right_in, R.anim.right_out);
					finish();
				}
			});
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.right_in, R.anim.right_out);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
			Intent i = new Intent(Bulletin.this, PDFdownloader.class);
			i.putExtra("Bulletin", 2);
			startService(i);
			overridePendingTransition(R.anim.right_in, R.anim.right_out);
			this.finish();
		}
		return true;
	}

	private String[] getFileName(File[] files, String[] string) {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < files.length; i++) {
			list.add(files[i].getName().toString()
					.substring(0, files[i].getName().length() - 4));
		}
		int size = list.size();
		string = (String[]) list.toArray(new String[size]);
		return string;
	}

	public void onRefreshStarted(View view) {
		ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cwjManager.getActiveNetworkInfo();
		if (info != null && info.isAvailable()) {
			Intent i = new Intent(Bulletin.this, PDFdownloader.class);
			i.putExtra("Bulletin", 1);
			startService(i);
		} else {
			new AsyncTask<Void, Void, Void>() {
				@Override
				protected Void doInBackground(Void... params) {
					return null;
				}

				@Override
				protected void onPostExecute(Void result) {
					super.onPostExecute(result);
					Toast.makeText(Bulletin.this, "No connection.",
							Toast.LENGTH_SHORT).show();
					mPullToRefreshAttacher.setRefreshComplete();
				}
			}.execute();
		}
	}
}